package com.matrix.draft.sockettest.day4;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.stream.IntStream;

public class NIOClient {
    public static void main(String[] args) {
        for (int j = 0; j < 10; j++) {
            new Thread(() -> {
                try {
                    SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(8080));
                    socketChannel.configureBlocking(false);
                    while (!socketChannel.finishConnect()) {
                        System.out.println("正在连接服务端中...");
                    }
                    IntStream.range(1, 11).forEach(i -> {
                        try {
                            Thread.sleep(500);
                            socketChannel.write(ByteBuffer.wrap(("你好啊NIO网络编程" + i).getBytes(StandardCharsets.UTF_8)));
                        } catch (IOException | InterruptedException e) {
                            e.printStackTrace();
                        }
                    });
                    socketChannel.shutdownOutput();
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }


    }
}
